import 'dart:async';

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
final textStyle = TextStyle(color: Color.fromRGBO(255, 255, 255, 1),decoration: TextDecoration.none,fontSize: 25.sp);

class DataGrid extends StatefulWidget {

  final List dataList;

  final int scrollBars;

  DataGrid({Key? key,required this.dataList,required this.scrollBars}):super(key: key);

  _DataGridState createState() => _DataGridState();

}

class _DataGridState extends State<DataGrid>{

  final DataGridController _controller = DataGridController();
  final ScrollController _verticalScrollController = ScrollController();

  late Timer _timer;

  double _currentRow = 0;

  late DataSource _dataSource;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _dataSource = DataSource(widget.dataList);
    _timer = Timer.periodic(Duration(seconds: 3), (Timer t) => autoScroll());
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  autoScroll(){
    if (_verticalScrollController.position.pixels ==
        _verticalScrollController.position.maxScrollExtent) {
      _currentRow = 0;
    }else{
      _currentRow += widget.scrollBars;
    }
    _controller.scrollToCell(_currentRow, 1,canAnimate:true);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SfDataGridTheme(
        data: SfDataGridThemeData(
          gridLineColor: Color.fromRGBO(46,47,83, 1.0),
          headerColor: Colors.blue,
          headerHoverColor: Colors.transparent,
        ),
        child:SfDataGrid(
          controller: _controller,
          verticalScrollController: _verticalScrollController,
          columnWidthMode: ColumnWidthMode.fill,
          source: _dataSource,
          rowHeight: 55.h,
          headerRowHeight: 55.h,
          gridLinesVisibility: GridLinesVisibility.both,
          headerGridLinesVisibility: GridLinesVisibility.both,
          columns: [
            GridColumn(
                columnName: 'no',
                maximumWidth: 100.r,
                label: Container(
                  // color: Colors.blue,
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '序号',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'workshop',
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '生产车间',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'productorderno',
                minimumWidth: 270.r,
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '生产单号',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'productCode',
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '零件图号',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'productName',
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '零件名称',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'productSpc',
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '规格型号',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'productQty',
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '计划数量',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'qtyDone',
                minimumWidth: 200.r,
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '已领数量',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),
            GridColumn(
                columnName: 'state',
                maximumWidth: 130.r,
                label: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    alignment: Alignment.center,
                    child: Text(
                      '状态',
                      style: textStyle,
                      overflow: TextOverflow.ellipsis,
                    ))),

          ],
        )
    );
  }

}

Widget buildSoftwareProficiency(dynamic value) {
  Widget getLinearProgressBar(num progressValue) {
    return Container(
      width: 120.r,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            height: 22.r,
            width: 120.r,
            child: ClipRRect(
              // 边界半径（`borderRadius`）属性，圆角的边界半径。
                borderRadius: BorderRadius.all(Radius.circular(10.0)),
                child: LinearProgressIndicator(
                  value: progressValue / 100,
                  valueColor: AlwaysStoppedAnimation<Color>(progressValue < 50 ? Colors.red : Colors.green),
                  backgroundColor:progressValue < 50 ? Colors.red[100] : Colors.green[100],
                )
            ),),
          Text(' ' + (progressValue.toString() + '%'),style: TextStyle(color: Color.fromRGBO(255, 255, 255, 1),decoration: TextDecoration.none,fontSize: 18.sp),
          ),
        ],
      ),
    );
  }

  return getLinearProgressBar(value);
}

class DataSource extends DataGridSource {
  final List<Color> _colors = [
    Colors.redAccent,
    Colors.deepPurpleAccent,
    Colors.greenAccent,
    Colors.orangeAccent,
    Colors.cyanAccent,
    Colors.deepOrangeAccent,
    Colors.indigoAccent,
    Colors.limeAccent,
    Colors.amberAccent,
  ];

  String oldWorkshop = "";
  int index = 0;

  DataSource(List dataList) {
    var index = 1;
    // 生产车间、生产单号、零件图号、零件名称、规格型号、计划数量、已领数量、状态
    dataGridRows = dataList
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
      DataGridCell<int>(columnName: 'no', value: index++),
      DataGridCell<String>(columnName: 'workshop', value: dataGridRow["workshop"][1]!=false?dataGridRow["workshop"][1]:""),
      DataGridCell<String>(columnName: 'productorderno', value: dataGridRow["productorderno"]!=false?dataGridRow["productorderno"]:""),
      DataGridCell<String>(columnName: 'productCode', value: dataGridRow["product"]["default_code"]!=false?dataGridRow["product"]["default_code"]:""),
      DataGridCell<String>(columnName: 'productName', value: dataGridRow["product"]["name"]!=false?dataGridRow["product"]["name"]:""),
      DataGridCell<String>(columnName: 'productSpc', value: dataGridRow["product"]["description"]!=false?dataGridRow["product"]["description"]:""),
      DataGridCell<String>(columnName: 'productQty', value: dataGridRow["product_qty"]!=false?dataGridRow["product_qty"].toString():""),
      DataGridCell<String>(columnName: 'qtyDone', value: dataGridRow["qty_done"]!=false?dataGridRow["qty_done"].toString():""),
      DataGridCell<String>(columnName: 'state', value: dataGridRow["state"]!=false?dataGridRow["state"]:""),
    ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    Color getRowBackgroundColor() {
      final String workshop = row.getCells()[1].value;
      if(oldWorkshop == ""){
        oldWorkshop = workshop;
      }
      if(workshop != oldWorkshop){
        oldWorkshop = workshop;
        if(index < _colors.length-1 ){
          index++;
        }else{
          index = 0;
        }
      }
      return _colors[index];
    }
    return DataGridRowAdapter(
        color: getRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          return dataGridCell.columnName == 'alarm'?buildSoftwareProficiency(dataGridCell.value):Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value.toString(),
                style: TextStyle(
                    fontSize: 18.sp,
                    color: Colors.black,
                    decoration: TextDecoration.none
                ),
                overflow: TextOverflow.ellipsis,
              ));
        }).toList());
  }
}
